package seeders

import (
	"goravel/app/models"

	"github.com/goravel/framework/facades"
)

type PermissionSeeder struct {
}

// Signature The name and signature of the seeder.
func (s *PermissionSeeder) Signature() string {
	return "PermissionSeeder"
}

// Run executes the seeder logic.
func (s *PermissionSeeder) Run() error {
	permissions := []map[string]any{
		// 用户管理权限
		{
			"perm_name": "用户列表",
			"perm_key":  "api/admin/users",
			"route":     "/api/admin/users",
		},
		{
			"perm_name": "用户详情",
			"perm_key":  "api/admin/users/{id}",
			"route":     "/api/admin/users/{id}",
		},
		{
			"perm_name": "创建用户",
			"perm_key":  "api/admin/users:POST",
			"route":     "/api/admin/users",
		},
		{
			"perm_name": "更新用户",
			"perm_key":  "api/admin/users/{id}:PUT",
			"route":     "/api/admin/users/{id}",
		},
		{
			"perm_name": "删除用户",
			"perm_key":  "api/admin/users/{id}:DELETE",
			"route":     "/api/admin/users/{id}",
		},
		{
			"perm_name": "获取当前用户",
			"perm_key":  "api/admin/user/getCurrentUser",
			"route":     "/api/admin/user/getCurrentUser",
		},
		// 分类管理权限
		{
			"perm_name": "分类列表",
			"perm_key":  "api/admin/categories",
			"route":     "/api/admin/categories",
		},
		{
			"perm_name": "分类详情",
			"perm_key":  "api/admin/categories/{id}",
			"route":     "/api/admin/categories/{id}",
		},
		{
			"perm_name": "创建分类",
			"perm_key":  "api/admin/categories:POST",
			"route":     "/api/admin/categories",
		},
		{
			"perm_name": "更新分类",
			"perm_key":  "api/admin/categories/{id}:PUT",
			"route":     "/api/admin/categories/{id}",
		},
		{
			"perm_name": "删除分类",
			"perm_key":  "api/admin/categories/{id}:DELETE",
			"route":     "/api/admin/categories/{id}",
		},
		{
			"perm_name": "获取下级分类ID",
			"perm_key":  "api/admin/categories/subordinate-ids",
			"route":     "/api/admin/categories/subordinate-ids",
		},
		// 权限管理权限
		{
			"perm_name": "权限列表",
			"perm_key":  "api/admin/permissions",
			"route":     "/api/admin/permissions",
		},
		// 角色管理权限
		{
			"perm_name": "角色列表",
			"perm_key":  "api/admin/roles",
			"route":     "/api/admin/roles",
		},
		{
			"perm_name": "更新角色",
			"perm_key":  "api/admin/roles/{id}:PUT",
			"route":     "/api/admin/roles/{id}",
		},
	}

	for _, permission := range permissions {
		var exists bool
		if err := facades.Orm().Query().Model(&models.Permission{}).Where("perm_key", permission["perm_key"].(string)).Exists(&exists); err != nil {
			facades.Log().Error("Failed to check existence: ", err)
			return err
		}

		if !exists {
			permissionModel := models.Permission{
				PermName: permission["perm_name"].(string),
				PermKey:  permission["perm_key"].(string),
				Route:    permission["route"].(string),
			}

			if err := facades.Orm().Query().Create(&permissionModel); err != nil {
				facades.Log().Error("Failed to create permission: ", err)
				return err
			}
		}
	}

	return nil
}
